package com.qiange.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiange.common.Result;
import com.qiange.dto.DishDto;
import com.qiange.dto.SetmealDto;
import com.qiange.exception.CustomException;
import com.qiange.pojo.Category;
import com.qiange.pojo.Setmeal;
import com.qiange.pojo.SetmealDish;
import com.qiange.service.CategoryService;
import com.qiange.service.SetmealDishService;
import com.qiange.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加套餐
     * @param setmealDto
     * @return
     * CacheEvict添加套餐后删除缓存，让移动端的用户能够实时查看最新数据
     */
    @CacheEvict(value = "setmeal:list", allEntries = true)
    @PostMapping
    public Result<String> add(@RequestBody SetmealDto setmealDto) {
        log.info(setmealDto.toString());

        setmealService.addWithDish(setmealDto);

        return Result.success("添加套餐成功");
    }

    /**
     * 分页查询套餐数据
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> selectByPage(int page, int pageSize, String name) {
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper();
        lqw.eq(name != null, Setmeal::getName, name);

        setmealService.page(setmealPage, lqw);


        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");

        //取出原有列表中的集合，集合中存放的是套餐信息
        //需要对这个集合进行处理，将分类名增加进去
        List<Setmeal> records = setmealPage.getRecords();

        List<SetmealDto> setmealDtoList = records.stream().map((record) -> {
            SetmealDto setmealDto = new SetmealDto();

            //将原有集合中的套餐对象信息拷贝到dto的对象中
            //拷贝完后，dto对象中还缺少一个套餐分类名称
            BeanUtils.copyProperties(record, setmealDto);

            //根据套餐分类id查询套餐分类名称，并封装到dto对象中
            Long categoryId = record.getCategoryId();
            //根据id查询套餐分类名称
            Category category = categoryService.getById(categoryId);
            setmealDto.setCategoryName(category.getName());

            return setmealDto;

        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(setmealDtoList);

        return Result.success(setmealDtoPage);
    }

    /**
     * 删除/批量删除套餐
     * @param ids
     * @return
     * CacheEvict删除套餐后删除缓存，让移动端的用户能够实时查看最新数据
     */
    @CacheEvict(value = "setmeal:list", allEntries = true)
    @DeleteMapping
    public Result<String> deleteByIds(@RequestParam List<Long> ids) {

        setmealService.removeWithDish(ids);

        return Result.success("删除成功");
    }

    /**
     * 修改套餐在售状态
     * @param status
     * @param ids
     * @return
     * CacheEvict修改套餐后删除缓存，让移动端的用户能够实时查看最新数据
     */
    @CacheEvict(value = "setmeal:list", allEntries = true)
    @PostMapping("/status/{status}")
    public Result<String> updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {

        List<Setmeal> setmealList = new ArrayList<>();

        for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setStatus(status);
            setmeal.setId(id);

            setmealList.add(setmeal);
        }

        setmealService.updateBatchById(setmealList);

        return Result.success("修改套餐状态成功");
    }

    /**
     * 根据id查找套餐数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<SetmealDto> selectById(@PathVariable Long id) {


        SetmealDto setmealDto = setmealService.selectByIdWithDish(id);

        return Result.success(setmealDto);
    }


    /**
     * 修改菜品数据
     * @param setmealDto
     * @return
     * CacheEvict修改菜品后删除缓存，让移动端的用户能够实时查看最新数据
     */
    @CacheEvict(value = "setmeal:list", key = "#setmealDto.categoryId")
    @PutMapping
    public Result<String> update(@RequestBody SetmealDto setmealDto) {
        log.info(setmealDto.toString());

        setmealService.updateWithDish(setmealDto);

        return Result.success("修改套餐信息成功");
    }

    /**
     * 查询套餐信息
     * @param setmeal
     * @return
     * 利用Cacheable实现套餐的缓存功能，替代原来的redisTemplate实现
     *  Cacheable会判断当前缓存的key是否有数据，如果没有数据，就将返回值存入缓存
     *  unless = "#result.data == null 如果result.data的值为空的话就不加入缓存
     */
    @Cacheable(value = "setmeal:list", key = "#setmeal.categoryId", unless = "#result.data == null")
    @GetMapping("/list")
    public Result<List<Setmeal>> list(Setmeal setmeal) {

        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        lambdaQueryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, 1);
        lambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> setmealList = setmealService.list(lambdaQueryWrapper);

        return Result.success(setmealList);

    }
}
